﻿<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>WebSocket客户端</title>
</head>

<script>
    var socket;
    // var M_Web_Socket_Url = "";
    var M_Web_Socket_Url = "";
    var contentDiv = null;
    var sendText = null;

    function BodyOnLoad() {
        var obj = findElementById("url");
        if (obj != null && obj != undefined) {
            obj.value = M_Web_Socket_Url;
        }
        var temp = Test();
        var obj = findElementById("infoDiv");
        if (obj != null && obj != undefined) {
            if (temp) {
                obj.innerText = "当前浏览器支持websocket!"
            } else {
                obj.innerText = "当前浏览器不支持websocket!"
            }
        }
    }

    function Test() {
        if (typeof (WebSocket) == "undefined") {
            return false;
        }
        return true;
    }

    function ConnectWS(url) {
        try {
            socket = new WebSocket(url);
            socket.onopen = OnOnpen;
            socket.onmessage = OnMsg;
            socket.onclose = OnClose;
            socket.onerror = OnError;
            console.debug("尝试连接Url:" + url);
            AppendTextToDiv("尝试连接Url:" + url);
        } catch (e) {
            console.error(e);
            AppendTextToDiv(e);
        }
    }

    function OnOnpen() {
        console.info("websocket open!");
        AppendTextToDiv("websocket open!");
    }

    function OnClose() {
        if (socket != null) {
            console.info("WebSocket close!");
            AppendTextToDiv("socket close!");
            var checkStr = GetCheckStatus("checkbox_autoConnect");
            if (checkStr != null && checkStr != undefined) {
                if (checkStr == true || checkStr == "on") {
                    Connect();
                }
            } else {
                return;
            }
        }
    }

    function OnMsg(msg) {
        var mprint = "";
        if (msg != null && msg != undefined)
            mprint = "收到消息,Msg:" + msg.data;
        else {
            mprint = "收到空消息";
        }
        console.debug(mprint);
        AppendTextToDiv(mprint);
    }

    function send(msg) {
        if (socket != null) {
            try {
                socket.send(msg);
                console.debug("Msg Send Ok! Msg:" + msg);
                AppendTextToDiv("Msg Send Ok! Msg:" + msg);
            } catch (error) {
                console.error(error);
                AppendTextToDiv(error);
            }
        }
    }

    function CloseWS() {
        if (socket != null && socket != undefined) {
            socket.close();
        }
    }

    function OnError(error) {
        console.debug("websocket 错误!");
        AppendTextToDiv("websocket 错误!" + error);
    }

    function Connect() {
        var url = GetUrlInput("url");
        ConnectWS(url);
    }

    function CheckStatus() {
        if (socket != null && socket != undefined) {
            var status = socket.readyState;
            var str;
            if (status == undefined) {
                str = "ReadyState: undefined;";
            } else {

                switch (status) {
                    case 0:
                        str = "连接尚未建立";
                        break;
                    case 1:
                        str = "连接已建立";
                        break;
                    case 2:
                        str = "连接正在进行关闭";
                        break;
                    case 3:
                        str = "连接已经关闭或者连接不能打开";
                        break;
                    default:
                        str = "未知状态:" + status;
                        break;
                }
            }
            console.info("连接状态：" + str);
            AppendTextToDiv("连接状态：" + str);
        }else{
            console.info("WebSocket为空或者未初始化");
            AppendTextToDiv("WebSocket为空或者未初始化");
        }
    }

    function GetUrlInput(id) {
        var obj = findElementById(id);
        if (obj != null && obj != undefined) {
            return obj.value;
        }
        return null;
    }

    function GetCheckStatus(id) {
        var obj = findElementById(id);
        if (obj != null && obj != undefined) {
            return obj.checked;
        }
        return null;
    }

    function findElementById(id) {
        if (id == undefined || id == null || id == "") {
            return undefined;
        }
        var obj = document.getElementById(id);
        return obj;
    }

    function AppendTextToDiv(msg) {
        if (contentDiv == null || contentDiv == undefined) {
            contentDiv = findElementById("contentDiv");
        }
        if (contentDiv != null && contentDiv != undefined) {
            contentDiv.innerText += msg + "\n\t";
        }
    }

    function ClearContext() {
        if (contentDiv != null && contentDiv != undefined) {
            contentDiv.innerText = "";
        }
    }

    function SendText() {
        if (sendText == null || sendText == undefined) {
            sendText = findElementById("sendTxt");
        }
        if (sendText != null && sendText != undefined) {
            try {
                var temp = sendText.value;
                send(temp);
                console.debug("发送成功！Msg:" + temp);
                AppendTextToDiv("发送成功！Msg:" + temp);
            } catch (error) {
                console.debug("发送错误！Error:" + error);
                AppendTextToDiv("发送错误！Error:" + error);
            }
        }
    }
</script>

<script>
    function CopyToClipkBoard() {
        var obj = findElementById("contentDiv");
        if(obj!=null&&obj !=undefined){
            var text = obj.innerText;
            const input = document.createElement('input');
            document.body.appendChild(input);
            input.setAttribute('value', text);
            input.select();
            if (document.execCommand('copy')) {
                console.log('复制成功');
                alert("复制成功");
            }
            document.body.removeChild(input);
        }
    }

    function SaveAsFile() {
        var obj = findElementById("contentDiv");
        if(obj!=null&&obj !=undefined){
            var text = obj.innerText;
            
            
        }
    }

    function SaveFile(text,file) {
        
    }

    var saveTextAsFile1 = function (text, fileName, success, error) {
    var data = text;
    if (!(text instanceof Array)) {
        data = [text];
    }
    var file = new File(data, fileName);
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function (r) {
        var url = reader.result;
        downLoadFile(url, fileName,
            function () {
                success && success();
            }, function () {
                error && error();
            });
    };
}
 
/**
 * 下载文件
 * @param {string, Array} text
 * @param {string} fileName
 * @param {function} success
 * @param {function} error
 */
var saveTextAsFile = function (text, fileName, success, error) {
        var data = text;
        if (!(text instanceof Array)) {
            data = [text];
        }
        var urlObject = window.URL || window.webkitURL || window;
        var export_blob = new Blob(data);
        var url = urlObject.createObjectURL(export_blob);
        downLoadFile(url, fileName,
            function () {
                success && success();
            }, function () {
                error && error();
            });
    }

</script>
<style>
    .MainDivStyle {
        align-items: baseline;
        left: 2%;
        top: 10px;
        width: 80%;
        position: relative;
        margin: 10px;
    }

    .ContentStyle {
        width: 90%;
        height: 80%;
        left: 2%;
        position: relative;
        background-color: lightblue;
        margin: 20px;
        overflow: auto;
        z-index: -99;
    }

    li.LiStype {
        margin: 10px;
        width: 80%;
    }
</style>

<body onload="BodyOnLoad()">
    <ul class="MainDivStyle">
        <li>
            <div id="infoDiv">...</div>
        </li>
        <li>
            <form item-width="80%">
                URL:
                <input type="text" name="urlN" id="url" width="80%" size="150">
            </form>
        </li>
        <li>
            <input type="checkbox" id="checkbox_autoConnect">
            <label>自动重连</label>
            </input>
            <button onclick="Connect()">连接</button>
            <button onclick="CloseWS()">关闭</button>
            <button onclick="CheckStatus()">检测状态</button>
        </li>
        <li>
            <button id="sendBtn" onclick="SendText();">发送</button>
            <input type="text" name="sendText" id="sendTxt" size="150" />
        </li>
        <li>
            <button onclick="ClearContext()">清空内容</button>
            <button onclick="CopyToClipkBoard()">复制到剪切板</button>
            <!-- <button onclick="CopyToClipkBoard()">另存文件</button> -->
        </li>
    </ul>
    <div id="contentDiv" class="ContentStyle">
    </div>
</body>

</html>